package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.kwd.rocketmq.RocketmqEvent;
import com.meirengu.channel.service.*;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.*;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.dao.UserInfoDao;
import com.meirengu.webview.model.*;
import com.meirengu.webview.service.*;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.meirengu.webview.common.ConfigConsts.CHANNEL_CODE_KAISEN;

/**
 * 2018-03-23 13:30:31  17689297129   2018-03-23 13:34:22  13761495811
 * UserInfo服务实现层
 *
 * @author maoruxin
 * @create Sun Dec 10 09:58:45 CST 2017
 */
@Service
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfo> implements UserInfoService {


    @Autowired
    SmsService smsService;

    @Autowired
    UserService userService;

    @Autowired
    KwChannelDataService kwChannelDataService;

    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    KwInterfaceConfigDao kwInterfaceConfigDao;

    @Autowired
    PingAnService pingAnService;

    @Autowired
    private KwYcdFilterService kwYcdFilterService;

    @Autowired
    KwUserChannelService kwUserChannelService;

    @Autowired
    NiWoDaiService niWoDaiService;

    @Autowired
    private KwDfrzFilterService kwDfrzFilterService;

    @Autowired
    PACAService pacaService;

    @Autowired
    HouBankService houBankService;

    @Autowired
    private KwZhudaiFilterService kwZhudaiFilterService;

    @Autowired
    KwFjsFilterService kwFjsFilterService;

    @Autowired
    private KwXxjrFilterService kwXxjrFilterService;

    @Autowired
    KwXbbFilterService kwXbbFilterService;

    @Autowired
    Feidan8Service feidan8Service;

    @Autowired
    XYCreditEaseService xyCreditEaseService;

    @Autowired
    private KwAydFilterService aydFilterService;

    @Autowired
    private KwCyphFilterService kwCyphFilterService;

    @Autowired
    private KwCcicFilterService kwCcicFilterService;

    @Autowired
    private KwPpdFilterService kwPpdFilterService;

    @Autowired
    ChinatopcreditService chinatopcreditService;

    @Autowired
    private KwWeidaiFilterService kwWeidaiFilterService;

    @Autowired
    private KwHnbFilterService kwHnbFilterService;

    @Autowired
    KwInterfaceLimitService kwInterfaceLimitService;

    @Autowired
    KwThirdbackService kwThirdbackService;

    @Autowired
    RedisClient redisClient;

    @Autowired
    private KwAydFilterService kwAydFilterService;


    @Autowired
    ProducerBean producer;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private KwAreaDataService kwAreaDataService;

    @Value("${producter.topic.kwd.product}")
    private String topicKwdProduct;
    @Value("${Tag.product.add}")
    private String tagProductAdd;
    @Value("${Tag.link.wechat}")
    private String tagLinkWechat;
    @Value("${Tag.link.marketing}")
    private String tagLinkMarketing;
    @Value("${Tag.immediately.echo}")
    private String tagImmediatelyEcho;
    @Value("${Tag.delay10M.echo}")
    private String tagDelay10Mecho;
    @Value("${Tag.delay24H.echo}")
    private String tagDelay24Hecho;

    Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    public Integer isExist(String userId) {
        return userInfoDao.isExist(userId);
    }


    /**
     * 遗留问题：
     * 1：如果是职业是企业主，营业执照时长使用工作时长字段，1年以上值为12
     *
     * @param request
     * @return
     * @throws Exception
     */
    public int complement(HttpServletRequest request) throws Exception {
        String param = request.getParameter("p");
        JSONObject paramJson = JSON.parseObject(param);
        //手机号
        String phoneno = paramJson.getString("phoneno");
        //姓名
        String name = paramJson.getString("name");
        //期望金额
        BigDecimal money = paramJson.getBigDecimal("money");
        //性别 0 男    1女
        Integer sex = paramJson.getInteger("sex");
        //所在城市
        String city = paramJson.getString("city");
        //职业  0白领   1私企业主  2公务员
        Integer profession = paramJson.getInteger("profession");
        //社保   0无社保   1一年以内    2一年以上
        Integer socialSecurity = paramJson.getInteger("socialSecurity");
        //住房公积金   0无公积金   1一年以内    2一年以上
        Integer housingFund = paramJson.getInteger("housingFund");
        //生日 格式“1991-08-09”
        Date birthday = paramJson.getDate("birthday");
        //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
        Integer income = paramJson.getInteger("income");
        //勾选意外险
        Integer insurance = paramJson.getInteger("insurance");
        //名下房产  1 无房   2 有房贷   3有房无贷
        Integer housingType = paramJson.getInteger("housingType");
        //名下车   1 无车   2 有车贷    3有车无贷
        Integer hasCar = paramJson.getInteger("hasCar");
        //信用情况 1无信用卡无贷款   2有信用卡或贷款
        Integer creditSituation = paramJson.getInteger("creditSituation");
        //工资发放方式  1 银行转账  2 现金发放
        Integer paytype = paramJson.getInteger("paytype");
        //工作时长  6 6个月内   12 12月内    24 一年以上
        Integer worklong = paramJson.getInteger("worklong");
        //接受用户协议
        Integer acceptsafety = paramJson.getInteger("acceptsafety");
        String infoJson = paramJson.getString("info");

        Integer enpass = 1;
        //寿险  1 无寿险   2 寿险2400以下   3 寿险2400以上
        Integer lifeInsurance = paramJson.getInteger("lifeInsurance");
        //是否用过微粒贷 1是，2否
        Integer isAtom = paramJson.getInteger("isAtom");
        //地区code
        Integer areaCode = paramJson.getInteger("areaCode");
        //地区name
        String areaName = paramJson.getString("areaName");
        //平台
        String plantform = paramJson.getString("plantform");
        //渠道
        String channel = paramJson.getString("channel");
        //渠道号
        String cid = paramJson.getString("cid");
        String requestid = paramJson.getString("requestid");
        String referer = paramJson.getString("referer");
        String fromUrl = paramJson.getString("fromUrl");
        String ip = RequestUtil.getClientIp(request);


        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phoneno);
        List<Map<String, Object>> userList = userService.getList(map);
        if (userList != null && userList.size() > 0) {
            for (Map<String, Object> userMap : userList) {
                String id = userMap.get("id").toString();
                Integer flag = isExist(id);
                //已保存
                if (flag != null && flag == 1) {
                    logger.info("已注册过：{}", phoneno);
                    return 0;
                } else {
                    //用户详细信息
                    UserInfo userInfo = new UserInfo();
                    userInfo.setExpectAmount(money);
                    userInfo.setPolicy(lifeInsurance);
                    userInfo.setCredit(creditSituation);
                    userInfo.setHouse(housingType);
                    userInfo.setCar(hasCar);
                    userInfo.setFund(housingFund);
                    userInfo.setSocialSecurity(socialSecurity);
                    userInfo.setOccupation(profession);
                    userInfo.setSalaryMethod(paytype);
                    userInfo.setWorkDuration(worklong);
                    userInfo.setSalary(income);
                    userInfo.setWxloan(isAtom);
                    userInfo.setScity(city);
                    userInfo.setBirthday(birthday);
                    userInfo.setBusinessDuration(enpass);
                    userInfo.setUserId(id);
                    userInfo.setIp(ip);
                    userInfo.setAreaCode(areaCode);
                    userInfo.setAreaName(areaName);
                    insert(userInfo);

                    //是否O2O
                    boolean O2Oflag = false;
                    if (lifeInsurance.intValue() != 1 || housingType.intValue() != 1 || hasCar.intValue() != 1) {
                        O2Oflag = true;
                    }
                    //更新产品申请量
                    if (userMap.get("channelId") != null) {
                        if (StringUtils.isNotBlank(userMap.get("channelId").toString())) {
                            int code = kwChannelDataService.updateApplyNum(userMap.get("channelId").toString(), O2Oflag);
                        }

                    }
                    //用户完善信息后的异步处理
                    sendAsyn(id);
                }
            }
        }
        return 0;
    }


    /**
     * 异步调用接口渠道
     *
     * @param userId
     */
    public boolean sendAsyn(String userId) {
        //发送甲方渠道
        immediately(userId);
        return true;
    }

    /**
     * 实时异步消息
     *
     * @param userId
     */
    public void immediately(String userId) {
        Message message = new Message();
        message.setTopic(topicKwdProduct);
        message.setTag(tagImmediatelyEcho);
        message.setBody(userId.getBytes());
        message.setKey("channel" + userId);
        producer.send(message);
        logger.info("immediately sendRocketMQ message :{}", message);
    }


    @EventListener(condition = "#event.tag=='registe_real_time'")
    public void immediatelyEcho(RocketmqEvent event) throws Exception {
        try {
            String id = event.getMsg();
            logger.info("id :{}", id);
            User user = userService.detail(id);
            UserInfo userInfo = userInfoDao.getByUserId(id);
            //发送信贷员系统，去掉状态判断，需要再加上
            String midasStatus = redisClient.get("ic-midasStatus");
            if ("Y".equals(midasStatus)) {
                sendProduct(user, userInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
    }

    /**
     * 延时消息：10分钟后关注公众号
     *
     * @param userId
     */
    public boolean sendMQlinkwechat(String userId) {
        //延时消息：10分钟后关注公众号
        Message message = new Message();
        message.setTopic(topicKwdProduct);
        message.setTag(tagLinkWechat);
        message.setBody(userId.getBytes());
        // 延时消息，单位毫秒（ms），在指定延迟时间（当前时间之后）进行投递，例如消息在 3 秒后投递
        //long delayTime = System.currentTimeMillis() + 3000;
        long delayTime = System.currentTimeMillis() + 1000 * 60 * 10;
        // 设置消息需要被投递的时间
        message.setStartDeliverTime(delayTime);
        message.setKey("wkqb" + userId);
        producer.send(message);
        logger.info("sendRocketMQ message :{}", message);
        return true;
    }


    /** rocketMQ接收消息  */
    /**
     * 延时消息：10分钟后关注公众号
     */
    @EventListener(condition = "#event.tag=='link_wechat'")
    public void consumerMQlinkwechat(RocketmqEvent event) throws Exception {
        try {
            String id = event.getMsg();
            User user = userService.detail(id);

            Calendar date = Calendar.getInstance();
            int hour = date.get(Calendar.HOUR_OF_DAY);
            if (hour > 8 && hour < 22) {
                /*String text = "【卡王贷】感谢您申请卡王贷，请用微信搜索并关注公众号“秒分配”，查询贷款进度，另有更多优质贷款产品为您推荐，无需额外验证码。退订回T";
                smsService.singleFollowSend(user.getMobile(), text);*/
                String url = ConfigUtil.getConfig("sms.send.url");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("phoneNumber", user.getMobile());
                jsonObject.put("templateCode", "SMS_05");
                HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            } else {
                redisClient.lpush("dcMQlinkwechat", user.getMobile());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }

    }

    /**
     * 延时消息：24小时  营销短信：超市
     *
     * @param userId
     */
    public boolean sendMQlinkMarketing(String userId) {
        //延时消息：10分钟后关注公众号
        Message message = new Message();
        message.setTopic(topicKwdProduct);
        message.setTag(tagLinkMarketing);
        message.setBody(userId.getBytes());
        // 延时消息，单位毫秒（ms），在指定延迟时间（当前时间之后）进行投递，例如消息在 3 秒后投递
        //long delayTime = System.currentTimeMillis() + 3000;
        long delayTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
        // 设置消息需要被投递的时间
        message.setStartDeliverTime(delayTime);
        message.setKey("marking" + userId);
        producer.send(message);
        logger.info("sendRocketMQ message :{}", message);
        return true;
    }
    /** rocketMQ接收消息  */
    /**
     * 延时消息：24小时  营销短信：超市
     */
    @EventListener(condition = "#event.tag=='link_marketing'")
    public void consumerMQlinkMarketing(RocketmqEvent event) throws Exception {
        try {
            String id = event.getMsg();
            User user = userService.detail(id);

            Calendar date = Calendar.getInstance();
            int hour = date.get(Calendar.HOUR_OF_DAY);
            if (hour > 8 && hour < 22) {
                String name = user.getName();
                if (StringUtils.isBlank(name)) {
                    name = "老铁";
                }
                /*String text = "【卡王贷】尊敬的" + name + ",根据您的资金需求及信用情况,您获得50000元贷款资格,戳 http://t.cn/RkPqcEH 申请。退订回T";
                smsService.singleSendMarketing(user.getMobile(), text);*/
                String url = ConfigUtil.getConfig("sms.send.url");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("phoneNumber", user.getMobile());
                jsonObject.put("templateCode", "SMS_06");
                JSONObject templateParam = new JSONObject();
                templateParam.put("name", name);
                jsonObject.put("templateParam", templateParam);
                HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            } else {
                redisClient.lpush("dcMQlinkmarketing", user.getMobile());
            }

            // 24小时后发送贷款机构
            if (StringUtils.isNotBlank(user.getName())) {
                // 判断是否已发送
                Map<String, Object> cyparams = new HashMap<>();
                cyparams.put("channelCode", "cyph");
                cyparams.put("mobile", user.getMobile());
                Integer cyphPushCount = kwCyphFilterService.getCount(cyparams);
                // 没有发送记录
                if (NumberUtil.isNullOrZero(cyphPushCount)) {
                    logger.info("未发送");
                    UserInfo userInfo = getByUserId(id);
                    sendChannel(user, userInfo);
                } else {
                    logger.info("已发送");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }

    }


    /**
     * 异步发送渠道
     *
     * @param user
     * @param userInfo
     * @throws Exception
     */
    public void sendChannel(User user, UserInfo userInfo) throws Exception {

        //平安普惠接口
        //过滤条件
        //1 年龄(21-55)
        //2 房车寿 三其一
        String puhuiStatus = redisClient.get("ic-pinganmarket");
        if ("Y".equals(puhuiStatus)) {
            sendPuHui(userInfo, user);
        }

        //平安赠险接口
        //过滤条件
        //1年龄(25-50)
        String pazxStatus = redisClient.get("ic-pinganzengxian");
        if ("Y".equals(pazxStatus)) {
            sendPingAnZX(userInfo, user);
        }

        //中腾信接口
        String ycdctcStatus = redisClient.get("ic-ycdctc");
        if ("Y".equals(ycdctcStatus)) {
            kwYcdFilterService.sendZTX(userInfo, user);
        }

        //你我贷接口
        //过滤条件
        //1地址
        String niwodaiStatus = redisClient.get("ic-niwodai");
        if ("Y".equals(niwodaiStatus)) {
            sendNiwodai(userInfo, user);
        }

        //东方融资网接口
        //过滤条件
        //1.地址
        String dfrzStatus = redisClient.get("ic-dfrz");
        if ("Y".equals(dfrzStatus)) {
            kwDfrzFilterService.sendEastFinance(userInfo, user);

        }

        //平安新一贷接口
        //过滤条件
        //1.年龄
        //2.地址
        //3.4其一
        String pcacStatus = redisClient.get("ic-pcac");
        if ("Y".equals(pcacStatus)) {
            sendPcac(userInfo, user);
        }
        // 发送助贷网接口
        // 过滤条件
        // 1有房、有车、有寿险保单（满足一个或多个属性皆可）
        // 2年龄25-55岁（含）
        // 3城市
        String zhudaiStatus = redisClient.get("ic-zhudai");
        if ("Y".equals(zhudaiStatus)) {
            userInfo.setCreateDate(new Date());
            kwZhudaiFilterService.sendZhuDai(userInfo, user);
        }
        //房金所接口
        String fjsStatus = redisClient.get("ic-fjs");
        if ("Y".equals(fjsStatus)) {
            kwFjsFilterService.sendFangGold(userInfo, user);

        }

        //厚本金融接口
        //过滤条件
        // 1 申请金额：2w以上
        // 2 满足城市字典
        // 3 年龄：21-60（包含21、60）
        // 4 收入：2000元以上
        // 5 有信用卡或者银行贷款
        // 6 公积金、保单（二者有其一）
        String houbankStatus = redisClient.get("ic-houbank");
        if ("Y".equals(houbankStatus)) {
            sendHouBank(userInfo, user);

        }

        //贷上我接口
        //过滤条件
        // 1.地区
        // 2.金额
        // 3.3其一
        String xxjrStatus = redisClient.get("ic-xxjr");
        if ("Y".equals(xxjrStatus)) {
            kwXxjrFilterService.sendWithMe(userInfo, user);

        }

        //贷上我2渠道接口
        //过滤条件
        // 1.地区
        // 2.金额
        // 3.3其一
        String xxjr2Status = redisClient.get("ic-xxjr2");
        if ("Y".equals(xxjr2Status)) {
            kwXxjrFilterService.sendWithMe2(userInfo, user);
        }

        //新贝接口
        String xbbStatus = redisClient.get("ic-xbb");
        if ("Y".equals(xbbStatus)) {
            kwXbbFilterService.sendXbb(userInfo, user);
        }
        //西伊宜信接口
        String xycrediteaseStatus = redisClient.get("ic-xycreditease");
        if ("Y".equals(xycrediteaseStatus)) {
            sendXYCreditEase(userInfo, user);
        }
        //飞单宝接口
        String feidan8Status = redisClient.get("ic-feidan8");
        if ("Y".equals(feidan8Status)) {
            sendFeidan8(userInfo, user);
        }
        //安易贷接口
        String aydStatus = redisClient.get("ic-ayd");
        if ("Y".equals(aydStatus)) {
            aydFilterService.sendAnyidai(userInfo, user);
        }
        //安易贷2接口
        String ayd2Status = redisClient.get("ic-ayd2");
        if ("Y".equals(ayd2Status)) {
            aydFilterService.sendAnyidai2(userInfo, user);
        }
        //安易贷3接口
        String ayd3Status = redisClient.get("ic-ayd3");
        if ("Y".equals(ayd3Status)) {
            aydFilterService.sendAnyidai3(userInfo, user);
        }
        //佳佳融接口
        String jjrStatus = redisClient.get("ic-jjr");
        if ("Y".equals(jjrStatus)) {
            kwHnbFilterService.sendJjr(userInfo, user);
        }
        //畅愿普惠接口
        String cyphStatus = redisClient.get("ic-cyph");
        if ("Y".equals(cyphStatus)) {
            userInfo.setCreateDate(new Date());
            kwCyphFilterService.sendChangYuanpuhui(userInfo, user);
        }
        //壹财道普惠接口
        String ycdphStatus = redisClient.get("ic-ycdph");
        if ("Y".equals(ycdphStatus)) {
            kwYcdFilterService.sendYCDPH(userInfo, user);
        }
        //畅愿普惠渠道2
        String cyph2Status = redisClient.get("ic-cyph2");
        if ("Y".equals(cyph2Status)) {
            userInfo.setCreateDate(new Date());
            kwCyphFilterService.sendChangYuanpuhui2(userInfo, user);
        }
        //大地接口
        String ccicStatus = redisClient.get("ic-ccic");
        if ("Y".equals(ccicStatus)) {
            userInfo.setCreateDate(new Date());
            kwCcicFilterService.sendCCIC(userInfo, user);
        }
        //拍拍贷接口
        String ppdaiStatus = redisClient.get("ic-ppdai");
        if ("Y".equals(ppdaiStatus)) {
            kwPpdFilterService.sendPpdai(userInfo, user);
        }
        //中腾信官方
        String ctcStatus = redisClient.get("ic-ctc");
        if ("Y".equals(ctcStatus)) {
            sendChinatopcredit(userInfo, user);
        }
        //微贷网
        String weidaiStatus = redisClient.get("ic-weidai");
        if ("Y".equals(weidaiStatus)) {
            kwWeidaiFilterService.sendWeidai(userInfo, user);
        }
        //畅愿保险接口
        String cyisStatus = redisClient.get("ic-cyis");
        if ("Y".equals(cyisStatus)) {
            userInfo.setCreateDate(new Date());
            kwCyphFilterService.sendChangYuanInsure(userInfo, user);
        }
        //畅愿保险接口
        String yijuStatus = redisClient.get("ic-yiju");
        if ("Y".equals(yijuStatus)) {
            userInfo.setCreateDate(new Date());
            kwFjsFilterService.sendYiJu(userInfo, user);
        }



        //闪借
        String shanjieStatus = redisClient.get("ic-shanjie");
        if ("Y".equals(shanjieStatus)) {
            userInfo.setCreateDate(new Date());
            kwAydFilterService.sendShanjie(userInfo, user);
        }

        //凯森
        String kaisenStatus = redisClient.get("ic-" + CHANNEL_CODE_KAISEN);
        if ("Y".equals(kaisenStatus)) {
            userInfo.setCreateDate(new Date());
            kwCyphFilterService.sendKaisen(userInfo, user);
        }
    }


    /**
     * 发送信贷员系统
     *
     * @param userInfo
     */
    public boolean sendProduct(User user, UserInfo userInfo) {
        try {
            String midasIol = redisClient.get("iol-midasStatus");
            if ("N".equals(midasIol)) {
                BigDecimal expectAmount = userInfo.getExpectAmount();
                if (expectAmount.compareTo(new BigDecimal(20000)) < 0) {
                    userInfo.setExpectAmount(new BigDecimal(20000));
                }
                JSONObject userInfoJson = (JSONObject) JSON.toJSON(userInfo);
                userInfoJson.put("mobile", user.getMobile());
                userInfoJson.put("name", user.getName());
                userInfoJson.put("sex", user.getSex());
                userInfoJson.put("channelId", user.getChannelId());
                userInfoJson.put("channelCode", user.getChannelCode());
                userInfoJson.put("channelName", user.getChannelName());
                Message message = new Message();
                message.setTopic(topicKwdProduct);
                message.setTag(tagProductAdd);
                message.setBody(userInfoJson.toJSONString().getBytes());
                message.setKey("midas" + user.getId());
                producer.send(message);
                logger.info("sendRocketMQ message :{}", message);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return false;
    }

    /**
     * 发送平安普惠接口
     * 过滤条件
     * 1 年龄(21-55)
     * 2 房车寿 三其一
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendPuHui(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String puhuiIol = redisClient.get("iol-pinganmarket");
            if ("N".equals(puhuiIol)) {
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();

                Integer hasCar = userInfo.getCar();
                String city = userInfo.getScity();
                Integer housingType = userInfo.getHouse();
                Integer lifeInsurance = userInfo.getPolicy();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer paytype = userInfo.getSalaryMethod();
                Integer creditSituation = userInfo.getCredit();
                Integer profession = userInfo.getOccupation();
                Integer income = userInfo.getSalary();
                Integer worklong = userInfo.getWorkDuration();
                Integer housingFund = userInfo.getFund();

                int age = 25;
                Date brithdayDate = userInfo.getBirthday();
                age = getAge(brithdayDate);


                KwUserChannel puhuikwUserChannel = new KwUserChannel();
                puhuikwUserChannel.setUserId(id);
                puhuikwUserChannel.setMobile(mobile);
                puhuikwUserChannel.setChannelCode("pinganpuhui");
                puhuikwUserChannel.setChannelName("平安普惠");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("pinganmarket");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            puhuikwUserChannel.setSuited("N");
                            puhuikwUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            puhuikwUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            puhuikwUserChannel.setSuited("N");
                            puhuikwUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            puhuikwUserChannel.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            puhuikwUserChannel.setSuited("N");
                            puhuikwUserChannel.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            puhuikwUserChannel.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "")) {

                            //平安字典：gender 性别 1.男 2.女
                            int aSex = sex.intValue() + 1;
                            //平安字典：income 收入 1 3000以下   2 3000~5000   3 5001~8000   4 8001~10000   5 10000+
                            //平安字典：payroll 发薪方式 1 现金发放   2 银行转账

                            //平安字典：loan_deadline 贷款期限 1 1-6个月 2 6-12个月 3 12-24个月 4 24个月以上
                            //平安字典：bank_loan 银行贷款 1 是 2 否
                            //平安字典：house_pledge 是否接受房产抵押 是否有房 1 是 2 否

                            String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                            //平安字典：car 是否有私家车 1 是   2 否
                            //平安字典：car_loan 是否在还车贷 1 是   2 否
                            int car = 2;
                            int carLoad = 2;
                            // 无车
                            if (hasCar.intValue() == 1) {
                                car = 2;
                                carLoad = 2;
                                //有车
                            } else if (hasCar.intValue() == 2) {
                                car = 1;
                                carLoad = 1;
                                //有车贷
                            } else if (hasCar.intValue() == 3) {
                                car = 1;
                                carLoad = 2;
                            }

                            //平安字典：life_insuranceTotal 寿险年保费合计 1 2400元以上   2 2400元以下
                            //平安字典：life_insurance  是否有寿险保单 1 是   2 否
                            int lifeInsuranceTotalVal = 1;
                            int lifeInsuranceVal = 1;
                            //无寿险
                            if (lifeInsurance.intValue() == 1) {
                                lifeInsuranceVal = 2;
                                //寿险2400以下
                            } else if (lifeInsurance.intValue() == 2) {
                                lifeInsuranceVal = 1;
                                lifeInsuranceTotalVal = 2;
                                //寿险2400以上
                            } else if (lifeInsurance.intValue() == 3) {
                                lifeInsuranceVal = 1;
                                lifeInsuranceTotalVal = 1;
                            }

                            //平安字典：injob 在职时长 1 6个月以下   2 6-12个月 3 12-24个月 4 24-36个月 5 36个月以上
                            int injobVal = 1;
                            //工作时长：6个月内
                            if (worklong.intValue() == 6) {
                                injobVal = 1;
                                //工作时长：12个月内
                            } else if (worklong.intValue() == 12) {
                                injobVal = 2;
                                //工作时长：1年以上
                            } else if (worklong.intValue() == 24) {
                                injobVal = 3;
                            }

                            //平安字典：house_loan 是否在还房贷 1 是   2 否
                            //平安字典：house 是否有房 1 是 2 否
                            int houseLoanVal = 1;
                            int house = 1;
                            if (housingType.intValue() == 1) {
                                house = 2;
                                houseLoanVal = 2;
                            } else if (housingType.intValue() == 2) {
                                house = 1;
                                houseLoanVal = 1;
                            } else if (housingType.intValue() == 3) {
                                house = 1;
                                houseLoanVal = 2;
                            }

                            //平安字典：card 是否有信用卡 1 是 2 否
                            int cardVal = 1;
                            if (creditSituation.intValue() == 2) {
                                cardVal = 1;
                            } else {
                                cardVal = 2;
                            }

                            //平安字典：loan_money 贷款金额 1 5万以下 2 5-10万 3 10-30万 4 30万以上
                            int loanMoneyVal = 1;
                            int loanMoneyUnitW = (expectAmount.divide(new BigDecimal(10000), 0, RoundingMode.FLOOR)).intValue();
                            if (loanMoneyUnitW < 5) {
                                loanMoneyVal = 1;
                            } else if (loanMoneyUnitW >= 5 && loanMoneyUnitW < 10) {
                                loanMoneyVal = 2;
                            } else if (loanMoneyUnitW >= 10 && loanMoneyUnitW < 30) {
                                loanMoneyVal = 3;
                            } else if (loanMoneyUnitW >= 30) {
                                loanMoneyVal = 4;
                            }
                            //平安字典：funds 公积金 1 是 2 否
                            int fundsVal = 1;
                            if (housingFund.intValue() == 0) {
                                fundsVal = 2;
                            } else {
                                fundsVal = 1;
                            }
                            //平安字典：jinpo 社保	 1 是 2 否
                            int jinpoVal = 1;
                            if (socialSecurity.intValue() == 0) {
                                jinpoVal = 2;
                            } else {
                                jinpoVal = 1;
                            }

                            //平安字典：profession 职业类别 1 公司职员   2 公务员   3 私营企业
                            int professionVal = 1;
                            //白领
                            if (profession.intValue() == 0) {
                                professionVal = 1;
                                //私企业主
                            } else if (profession.intValue() == 1) {
                                professionVal = 3;
                                //公务员
                            } else if (profession.intValue() == 2) {
                                professionVal = 2;
                            }
                            Integer code = pingAnService.puhuiAdd(name, aSex + "", mobile, birthdayStr, income + "",
                                    ((paytype == 1) ? 2 : 1) + "", car + "", (lifeInsuranceVal == 2) ? "" : (lifeInsuranceTotalVal + ""), professionVal + "",
                                    injobVal + "", houseLoanVal + "", carLoad + "", cardVal + "", lifeInsuranceVal + "",
                                    loanMoneyVal + "", "", "", fundsVal + "", jinpoVal + "",
                                    "", house + "", "");
                            puhuikwUserChannel.setSuited("Y");
                            puhuikwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            updateLimitNum(code, "pinganmarket", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            puhuikwUserChannel.setSuited("N");
                            puhuikwUserChannel.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            puhuikwUserChannel.setRefuseMsg("无房:" + housingType.intValue() + " 无车: " + hasCar.intValue() + " 无保单: " + lifeInsurance.intValue());
                        }
                    }
                }
                kwUserChannelService.insert(puhuikwUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 发送春雨赠险未完善数据
     * 过滤条件
     * 1 1年龄(25-50)
     *
     * @param user
     * @throws Exception
     */
    public boolean sendCYZXWWS(User user) throws Exception {

        boolean sendFlag = false;
        try {
            String id = user.getId();
            String name = user.getName();
            String mobile = user.getMobile();
            Integer sex = user.getSex();
            String ip = user.getIp();

            int age = 25;
            Date brithdayDate = user.getBirthday();
            age = getAge(brithdayDate);


            KwUserChannel pazxKwUserChannel = new KwUserChannel();
            pazxKwUserChannel.setUserId(id);
            pazxKwUserChannel.setMobile(mobile);
            pazxKwUserChannel.setChannelCode("pinganzenxian");
            pazxKwUserChannel.setChannelName("平安赠险");
//                  kwUserChannel.setThirdBackId();
            if (age > 24 && age < 51) {
                int aSex = sex.intValue() + 1;
                String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                Integer code = pingAnService.renshouAdd(name, aSex + "", mobile, birthdayStr, ip, "", "");
                pazxKwUserChannel.setSuited("Y");
                pazxKwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                /*推送接口后修改限制数量*/
                updateLimitNum(code, "pinganzengxian", user);
                if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                    sendFlag = true;
                }
            } else {
                pazxKwUserChannel.setSuited("N");
                pazxKwUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                pazxKwUserChannel.setRefuseMsg("年龄小于25或大于50：" + age);
            }
            kwUserChannelService.insert(pazxKwUserChannel);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 发送平安赠险接口
     * 过滤条件
     * 1 1年龄(25-50)
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendPingAnZX(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String pazxIol = redisClient.get("iol-pinganzengxian");
            if ("N".equals(pazxIol)) {
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();

                Integer hasCar = userInfo.getCar();
                Integer housingType = userInfo.getHouse();
                String ip = userInfo.getIp();

                int age = 25;
                Date brithdayDate = userInfo.getBirthday();
                age = getAge(brithdayDate);


                KwUserChannel pazxKwUserChannel = new KwUserChannel();
                pazxKwUserChannel.setUserId(id);
                pazxKwUserChannel.setMobile(mobile);
                pazxKwUserChannel.setChannelCode("pinganzenxian");
                pazxKwUserChannel.setChannelName("平安赠险");
//                  kwUserChannel.setThirdBackId();
                if (age > 24 && age < 51) {
                    int aSex = sex.intValue() + 1;
                    String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                    Integer code = pingAnService.renshouAdd(name, aSex + "", mobile, birthdayStr, ip, ((hasCar == 1) ? 0 : 1) + "", ((housingType == 1) ? 0 : 1) + "");
                    pazxKwUserChannel.setSuited("Y");
                    pazxKwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                    /*推送接口后修改限制数量*/
                    updateLimitNum(code, "pinganzengxian", user);
                    if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                        sendFlag = true;
                    }
                } else {
                    pazxKwUserChannel.setSuited("N");
                    pazxKwUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                    pazxKwUserChannel.setRefuseMsg("年龄小于25或大于50：" + age);
                }
                kwUserChannelService.insert(pazxKwUserChannel);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 发送你我贷接口
     * 过滤条件
     * 1地址
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendNiwodai(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String niwodaiIol = redisClient.get("iol-niwodai");
            if ("N".equals(niwodaiIol)) {
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                String city = userInfo.getScity();
                BigDecimal expectAmount = userInfo.getExpectAmount();

                int age = 25;
                Date brithdayDate = userInfo.getBirthday();
                age = getAge(brithdayDate);

                KwUserChannel niwodaikwUserChannel = new KwUserChannel();
                niwodaikwUserChannel.setUserId(id);
                niwodaikwUserChannel.setMobile(mobile);
                niwodaikwUserChannel.setChannelCode("niwodai");
                niwodaikwUserChannel.setChannelName("你我贷");
                if (!StringUtil.isEmpty(city)) {
                    city = city.replace("市", "");
                    if (ConfigUtil.getConfig("niwodai.city.allow").contains(city)) {
                        String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                        Integer code = niWoDaiService.loanApplication(mobile, name, age + "", birthdayStr, city, expectAmount + "");
                        niwodaikwUserChannel.setSuited("Y");
                        niwodaikwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                        /*推送接口后修改限制数量*/
                        updateLimitNum(code, "niwodai", user);
                        if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                            sendFlag = true;
                        }
                    } else {
                        niwodaikwUserChannel.setSuited("N");
                        niwodaikwUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                        niwodaikwUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                    }
                }
                kwUserChannelService.insert(niwodaikwUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }


    /**
     * 发送平安新一贷接口
     * 过滤条件
     * 1.年龄
     * 2.地址
     * 3.3其一（房车寿修改为房，公积金，寿）
     *
     * @param userInfo
     * @param user
     */
    public boolean sendPcac(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String pcacIol = redisClient.get("iol-pcac");
            if ("N".equals(pcacIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                String city = userInfo.getScity();
                Integer creditSituation = userInfo.getCredit();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer worklong = userInfo.getWorkDuration();
                Integer housingFund = userInfo.getFund();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                int age = 25;
                age = getAge(brithdayDate);

                KwUserChannel pacaKwUserChannel = new KwUserChannel();
                pacaKwUserChannel.setUserId(id);
                pacaKwUserChannel.setMobile(mobile);
                pacaKwUserChannel.setChannelCode("paca");
                pacaKwUserChannel.setChannelName("平安新一贷");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("pcac");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            pacaKwUserChannel.setSuited("N");
                            pacaKwUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            pacaKwUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            pacaKwUserChannel.setSuited("N");
                            pacaKwUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            pacaKwUserChannel.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            pacaKwUserChannel.setSuited("N");
                            pacaKwUserChannel.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            pacaKwUserChannel.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "") ||
                                kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "")) {

                            String userCreditCard = "YES";
                            //信用情况 1无信用卡无贷款   2有信用卡或贷款
                            if (creditSituation.intValue() == 1) {
                                userCreditCard = "NO";
                            }
                            String liveTime = "01";
                            //工作时长  6 6个月内   12 12月内    24 一年以上
                            if (worklong.intValue() == 6) {
                                liveTime = "02";
                            }
                            String houseLoan = "YES";
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            if (housingType.intValue() != 2) {
                                houseLoan = "NO";
                            }
                            String userCar = "YES";
                            //名下车   1 无车   2 有车贷    3有车无贷
                            if (hasCar.intValue() == 1) {
                                userCar = "NO";
                            }
                            String insurancePolicy = "YES";
                            //寿险  1 无寿险   2 寿险2400以下   3 寿险2400以上
                            if (lifeInsurance.intValue() == 1) {
                                insurancePolicy = "NO";
                            }
                            Integer code = pacaService.applyLoan(name, "23-55岁", mobile, city, userCreditCard,
                                    liveTime, houseLoan, userCar, insurancePolicy);
                            pacaKwUserChannel.setSuited("Y");
                            pacaKwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            updateLimitNum(code, "pcac", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            pacaKwUserChannel.setSuited("N");
                            pacaKwUserChannel.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            pacaKwUserChannel.setRefuseMsg("无保单：" + lifeInsurance.intValue() + " 无房：" +
                                    housingType.intValue() + " 无车：" + hasCar.intValue());
                        }
                    }
                }

                kwUserChannelService.insert(pacaKwUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }


    /**
     * 发送厚本金融接口
     * 过滤条件
     * 1 申请金额：2w以上
     * 2 满足城市字典
     * 3 年龄：21-60（包含21、60）
     * 4 收入：2000元以上
     * 5 有信用卡或者银行贷款
     * 6 公积金、保单（二者有其一）
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendHouBank(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String fgIol = redisClient.get("iol-fanggold");
            if ("N".equals(fgIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer housingFund = userInfo.getFund();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer profession = userInfo.getOccupation();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer income = userInfo.getSalary();
                Integer creditSituation = userInfo.getCredit();
                Integer paytype = userInfo.getSalaryMethod();
                Integer socialSecurity = userInfo.getSocialSecurity();

                int age = 25;
                age = getAge(brithdayDate);

                KwUserChannel hbKwUserChannel = new KwUserChannel();
                hbKwUserChannel.setUserId(id);
                hbKwUserChannel.setMobile(mobile);
                hbKwUserChannel.setChannelCode("houbank");
                hbKwUserChannel.setChannelName("厚本金融");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("houbank");


                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            hbKwUserChannel.setSuited("N");
                            hbKwUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            hbKwUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            hbKwUserChannel.setSuited("N");
                            hbKwUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            hbKwUserChannel.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            hbKwUserChannel.setSuited("N");
                            hbKwUserChannel.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            hbKwUserChannel.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitCredit())) {
                        if (kwInterfaceConfig.getCreditValue().contains(creditSituation.intValue() + "")) {
                            dataFlag = false;
                            hbKwUserChannel.setSuited("N");
                            hbKwUserChannel.setCode(UserChannelEnum.FAIL_NO_CREDIT.getValue());
                            hbKwUserChannel.setRefuseMsg("用户无信用卡无贷款：" + creditSituation.intValue());
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "") ||
                                kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "")) {

                            String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                            //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
                            int incoming = 0;
                            String incomeRange = "";
                            if (income.intValue() == 1) {
                                incoming = 3000;
                                incomeRange = "3";
                            } else if (income.intValue() == 2) {
                                incoming = 5000;
                                incomeRange = "3";
                            } else if (income.intValue() == 3) {
                                incoming = 8000;
                                incomeRange = "2";
                            } else if (income.intValue() == 4) {
                                incoming = 10000;
                                incomeRange = "2";
                            } else if (income.intValue() == 5) {
                                incoming = 20000;
                                incomeRange = "1";
                            }
                            //职业  0白领   1私企业主  2公务员
                            //工资发放方式  1 银行转账  2 现金发放
                            //社保   0无社保   1一年以内    2一年以上
                            //住房公积金   0无公积金   1一年以内    2一年以上
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            //名下车   1 无车   2 有车贷    3有车无贷
                            String isHasCar = "";
                            String isCarLoan = null;
                            if (hasCar.intValue() == 1) {
                                isHasCar = "2";
                            } else if (hasCar.intValue() == 2) {
                                isHasCar = "1";
                                isCarLoan = "3";
                            } else if (hasCar.intValue() == 3) {
                                isHasCar = "1";
                                isCarLoan = "1";
                            }
                            String custSex = "01";
                            if (sex.intValue() == 1) {
                                custSex = "02";
                            }
                            Integer code = houBankService.applyLoan(id, name, mobile, birthdayStr, incoming,
                                    null, null, city, (profession.intValue() + 1) + "",
                                    incomeRange, paytype + "", "1",
                                    (socialSecurity.intValue() == 0 ? 2 : 1) + "",
                                    (housingFund.intValue() == 0 ? 2 : 1) + "", isHasCar, isCarLoan,
                                    (housingType.intValue() == 1 ? 2 : 1) + "",
                                    (lifeInsurance.intValue() == 1 ? 2 : 1) + "",
                                    null, custSex, null, null, null,
                                    expectAmount + "", null);
                            hbKwUserChannel.setSuited("Y");
                            hbKwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            updateLimitNum(code, "houbank", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            hbKwUserChannel.setSuited("N");
                            hbKwUserChannel.setCode(UserChannelEnum.FAIL_FUND.getValue());
                            hbKwUserChannel.setRefuseMsg("用户无公积金：" + housingFund.intValue() + " 无保单：" + lifeInsurance.intValue());
                        }
                    }
                }

                kwUserChannelService.insert(hbKwUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 通过userId获取用户详细信息
     *
     * @param userId
     * @return
     */
    public UserInfo getByUserId(String userId) {
        return userInfoDao.getByUserId(userId);
    }

    //由出生日期获得年龄
    public int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }


    /**
     * 发送西伊宜信接口
     * 过滤条件
     * 1.地区
     * 2.年龄
     * 3.金额  2000
     * 4.4其一
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendXYCreditEase(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String xycrediteaseIol = redisClient.get("iol-xycreditease");
            if ("N".equals(xycrediteaseIol)) {
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();

                String city = userInfo.getScity();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer housingType = userInfo.getHouse();
                Integer carType = userInfo.getCar();
                Integer profession = userInfo.getOccupation();
                Integer salaryMethod = userInfo.getSalaryMethod();
                Integer income = userInfo.getSalary();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer housingFund = userInfo.getFund();
                Integer worklong = userInfo.getWorkDuration();
                Integer lifeInsurance = userInfo.getPolicy();


                int age = 25;
                Date brithdayDate = userInfo.getBirthday();
                age = getAge(brithdayDate);


                KwUserChannel xyUserChannel = new KwUserChannel();
                xyUserChannel.setUserId(id);
                xyUserChannel.setMobile(mobile);
                xyUserChannel.setChannelCode("xycreditease");
                xyUserChannel.setChannelName("西伊宜信");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("xycreditease");


                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            xyUserChannel.setSuited("N");
                            xyUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            xyUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            xyUserChannel.setSuited("N");
                            xyUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            xyUserChannel.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            xyUserChannel.setSuited("N");
                            xyUserChannel.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            xyUserChannel.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "") ||
                                kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(carType.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "")) {

                            String birthDate = DateUtils.dateToStr(brithdayDate, "yyyyMMdd");
                            String hasHouse = (housingType - 1) + "";
                            String hasCar = (carType - 1) + "";
                            String job = "0";
                            //白领
                            if (profession.intValue() == 0) {
                                job = "0";
                                //私企业主
                            } else if (profession.intValue() == 1) {
                                job = "2";
                                //公务员
                            } else if (profession.intValue() == 2) {
                                job = "1";
                            }
                            String salaryPayType = "0";
                            if (salaryMethod.intValue() == 2) {
                                salaryPayType = "1";
                            }
                            //默认：2w
                            String salary = "20000";
                            //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
                            if (income.intValue() == 1) {
                                salary = "3000";
                            } else if (income.intValue() == 2) {
                                salary = "5000";
                            } else if (income.intValue() == 3) {
                                salary = "8000";
                            } else if (income.intValue() == 4) {
                                salary = "10000";
                            }
                            String socialInsurance = "1";
                            if (socialSecurity.intValue() == 0) {
                                socialInsurance = "2";
                            } else if (socialSecurity.intValue() == 1) {
                                socialInsurance = "0";
                            }
                            String houseInsurance = "1";
                            if (housingFund.intValue() == 0) {
                                houseInsurance = "0";
                            }

                            String jobTime = "3";
                            //工作时长：6个月内
                            if (worklong.intValue() == 6) {
                                jobTime = "0";
                                //工作时长：12个月内
                            } else if (worklong.intValue() == 12) {
                                jobTime = "1";
                                //工作时长：1年以上
                            } else if (worklong.intValue() == 24) {
                                jobTime = "2";
                            }

                            String insurance = "2";
                            //无寿险
                            if (lifeInsurance.intValue() == 1) {
                                insurance = "0";
                                //寿险2400以下
                            } else if (lifeInsurance.intValue() == 2) {
                                insurance = "1";
                                //寿险2400以上
                            }

                            Integer code = xyCreditEaseService.applyLoan(name, sex + "", mobile, birthDate,
                                    city.replace("市", ""), (expectAmount.intValue()) + "",
                                    hasHouse, hasCar, job, salaryPayType, salary,
                                    socialInsurance, houseInsurance, jobTime, insurance);
                            xyUserChannel.setSuited("Y");
                            xyUserChannel.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            updateLimitNum(code, "xycreditease", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            xyUserChannel.setSuited("N");
                            xyUserChannel.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            xyUserChannel.setRefuseMsg("无房:" + housingType.intValue() + " 无车: " + carType.intValue()
                                    + " 无保单: " + lifeInsurance.intValue() + " 无公积金: " + housingFund.intValue());
                        }
                    }
                }
                kwUserChannelService.insert(xyUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 发送飞单宝接口
     * 过滤条件
     * 1.客户贷款需求≥2万 ；
     * 2.客户年龄硬大于等于22周岁且小于等于55周岁；
     * 3.客户的申请ip地址与客户的手机号一致；
     * 4.客户至少拥有“打卡、社保、公积金、清房、按揭房、清车、按揭车、保单、微粒贷”中一个条件。
     * 银行卡转账，社保，公积金，有房，有车，保单
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendFeidan8(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String feidan8Iol = redisClient.get("iol-feidan8");
            if ("N".equals(feidan8Iol)) {
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer housingType = userInfo.getHouse();
                Integer carType = userInfo.getCar();
                Integer salaryMethod = userInfo.getSalaryMethod();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer housingFund = userInfo.getFund();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer wxloan = userInfo.getWxloan();
                String city = userInfo.getScity();
                int age = 25;
                Date brithdayDate = userInfo.getBirthday();
                age = getAge(brithdayDate);

                KwUserChannel fdUserChannel = new KwUserChannel();
                fdUserChannel.setUserId(user.getId());
                fdUserChannel.setMobile(user.getMobile());
                fdUserChannel.setChannelCode("feidan8");
                fdUserChannel.setChannelName("飞单宝");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("feidan8");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            fdUserChannel.setSuited("N");
                            fdUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            fdUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            fdUserChannel.setSuited("N");
                            fdUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            fdUserChannel.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            fdUserChannel.setSuited("N");
                            fdUserChannel.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            fdUserChannel.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getSalaryMethodValue().contains(salaryMethod.intValue() + "") ||
                                kwInterfaceConfig.getSocialSecurityValue().contains(socialSecurity.intValue() + "") ||
                                kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "") ||
                                kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(carType.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "") ||
                                kwInterfaceConfig.getWxloanValue().contains(wxloan.intValue() + "")) {

                            Integer code = feidan8Service.applyLoan(user, userInfo);
                            fdUserChannel.setSuited("Y");
                            fdUserChannel.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            updateLimitNum(code, "feidan8", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            fdUserChannel.setSuited("N");
                            fdUserChannel.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            fdUserChannel.setRefuseMsg("非打卡" + salaryMethod.intValue() + " 无社保:" + socialSecurity.intValue() + " 无房:" + housingType.intValue() + " 无车: " + carType.intValue()
                                    + " 无保单: " + lifeInsurance.intValue() + " 无公积金: " + housingFund.intValue() + " 无微粒贷: " + wxloan.intValue());
                        }
                    }
                }
                kwUserChannelService.insert(fdUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 秒单之家多余数据发送飞单宝
     */
    @EventListener(condition = "#event.tag=='mdzj_to_feidan8'")
    public void productAdd(RocketmqEvent event) throws Exception {
        try {
            JSONObject jsonObject = JSON.parseObject(event.getMsg());
            String dataStr = jsonObject.getString("data");
            dataStr = dataStr.substring(1, dataStr.length() - 1);
            dataStr.replace("\"", "");
            String str[] = dataStr.split(",");
            String uuid = null;
            for (int i = 0; i < str.length; i++) {
                uuid = str[i].substring(1, str[i].length() - 1);
                if (StringUtils.isNotBlank(uuid) && uuid.length() > 10) {
                    //查找kwuserinfo
                    UserInfo userInfo = detail(uuid);
                    User user = userService.detail(userInfo.getUserId());
                    sendFeidan8(userInfo, user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }


    }


    /**
     * 发送中腾信官方接口
     * 过滤条件
     * 1.城市
     * 2.年龄：23-55
     * 3.公积金
     * 4.职业：工薪族或公务员（私企业主转为工薪族）
     * 5.月收入2000以上
     *
     * @param userInfo
     * @param user
     * @throws Exception
     */
    public boolean sendChinatopcredit(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String ctcIol = redisClient.get("iol-ctc");
            if ("N".equals(ctcIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer housingFund = userInfo.getFund();
                Integer lifeInsurance = userInfo.getPolicy();
                Integer profession = userInfo.getOccupation();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer income = userInfo.getSalary();
                String ip = userInfo.getIp();
                Integer creditSituation = userInfo.getCredit();
                Integer paytype = userInfo.getSalaryMethod();
                Integer socialSecurity = userInfo.getSocialSecurity();

                int age = 25;
                age = getAge(brithdayDate);
                int aSex = sex.intValue() + 1;
                String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");

                KwUserChannel kwUserChannel = new KwUserChannel();
                kwUserChannel.setUserId(id);
                kwUserChannel.setMobile(mobile);
                kwUserChannel.setChannelCode("ctc");
                kwUserChannel.setChannelName("中腾信官方");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("ctc");

                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwUserChannel.setSuited("N");
                            kwUserChannel.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwUserChannel.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwUserChannel.setSuited("N");
                            kwUserChannel.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwUserChannel.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwUserChannel.setSuited("N");
                            kwUserChannel.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwUserChannel.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitFund())) {
                        if (!kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "")) {
                            dataFlag = false;
                            kwUserChannel.setSuited("N");
                            kwUserChannel.setCode(UserChannelEnum.FAIL_FUND.getValue());
                            kwUserChannel.setRefuseMsg("没有公积金：" + housingFund.intValue());
                        }
                    }
                    if (dataFlag) {
                        //公积金或社保加车或社保加房
                        if (kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "") ||
                                (kwInterfaceConfig.getSocialSecurityValue().contains(socialSecurity.intValue() + "") && kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "")) ||
                                (kwInterfaceConfig.getSocialSecurityValue().contains(socialSecurity.intValue() + "") && kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + ""))) {

                            String incomeVal = "10000以上";
                            //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
                            if (income.intValue() == 1) {
                                incomeVal = "2000-2999";
                            } else if (income.intValue() == 2) {
                                incomeVal = "3000-3999";
                            } else if (income.intValue() == 3) {
                                incomeVal = "4000-5999";
                            } else if (income.intValue() == 4) {
                                incomeVal = "6000-9999";
                            }
                            String vocation = "工薪族";
                            if (profession.intValue() == 2) {
                                vocation = "公务员";
                            }
                            Integer code = chinatopcreditService.applyLoan(id, name, mobile, city, vocation, incomeVal);
                            kwUserChannel.setSuited("Y");
                            kwUserChannel.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            updateLimitNum(code, "ctc", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            kwUserChannel.setSuited("N");
                            kwUserChannel.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            kwUserChannel.setRefuseMsg("社保：" + socialSecurity.intValue() + "公积金：" + housingFund.intValue() + " 车：" + hasCar.intValue() + " 房：" + housingType.intValue());
                        }
                    }
                }

                kwUserChannelService.insert(kwUserChannel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }


    /**
     * 推送接口后修改限制数量
     *
     * @param code
     * @param interfaceCode
     * @param user
     */
    public void updateLimitNum(Integer code, String interfaceCode, User user) {

        // 新功能
        try {
            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                /*更新数据库*/
                KwInterfaceLimit kwInterfaceLimit = new KwInterfaceLimit();
                kwInterfaceLimit.setInterfaceCode(interfaceCode);
                kwInterfaceLimit.setLastMobile(user.getMobile());
                kwInterfaceLimit.setLastCreateDate(user.getCreateDate());
                kwInterfaceLimitService.updateLimitNum(kwInterfaceLimit);
            }
            /*该接口是否限制数量*/
            String isLimitNum = redisClient.get("iln-" + interfaceCode);
            /*如果限制数量需要更新数量*/
            if ("Y".equals(isLimitNum)) {
                /*推送成功，更新缓存中限制数量，更新数据库中已发送数量*/
                if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                    String num = redisClient.get("limit-num-" + interfaceCode);
                    if (StringUtils.isNotBlank(num)) {
                        Integer numValue = Integer.parseInt(num);
                        Integer newNum = numValue.intValue() - 1;
                        if (newNum.intValue() <= 0) {
                            /*接口推送数量超过限制*/
                            redisClient.set("iol-" + interfaceCode, "Y");
                        } else {
                            redisClient.set("limit-num-" + interfaceCode, newNum.toString());
                        }
                    }

                } else if (code.intValue() == Constants.BUSINESS_STATUS_OUT_LIMIT) {
                    /*接口推送数量超过限制*/
                    redisClient.set("iol-" + interfaceCode, "Y");
                }
                String iolStatus = redisClient.get("iol-" + interfaceCode);
                if ("Y".equals(iolStatus)) {
                    /*更新数据库*/
                    KwInterfaceLimit kwInterfaceLimit = new KwInterfaceLimit();
                    kwInterfaceLimit.setInterfaceCode(interfaceCode);
                    kwInterfaceLimitService.updateOutLimit(kwInterfaceLimit);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }

    }


    /**
     * 推送接口后按地区修改限制数量
     *
     * @param code
     * @param channelCode
     * @param user
     * @param userInfo
     */
    @Override
    public void updateAreaLimit(Integer code, String channelCode, UserInfo userInfo, User user) {
        try {
            String flag = "N";
            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                /*更新数据库*/
                KwAreaData kwAreaData = new KwAreaData();
                kwAreaData.setLastCreateTime(user.getCreateDate());
                kwAreaData.setLastMobile(user.getMobile());
                kwAreaData.setChannelCode(channelCode);
                kwAreaData.setAreaCode(userInfo.getAreaCode());
                int count = kwAreaDataService.updatePushNum(kwAreaData);
                // 没有更新数量则判断是否超出数量，防止redis出错时程序出现bug
                if (count == 0) {
                    Map<String, Object> map = new HashMap<>();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    map.put("areaCode", userInfo.getAreaCode());
                    map.put("channelCode", "zhudai");
                    map.put("dataDate", sdf.format(new Date()));
                    List<KwAreaData> list = kwAreaDataService.getModel(map);
                    if (list.size() == 1) {
                        if (list.get(0).getPushNum().equals(list.get(0).getNum())) {
                            flag = "Y";
                        }
                    }
                }
            }
            /*该接口是否限制数量*/
            String isLimitNum = redisClient.hget("ald-" + channelCode, "area_limit_" + userInfo.getAreaCode());
            if ("Y".equals(isLimitNum)) {
                /*推送成功，更新缓存中限制数量，更新数据库中已发送数量*/
                if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                    Long num = redisClient.hincrBy("ald-" + channelCode, "limit_num_" + userInfo.getAreaCode(), -1);
                    Integer newNum = num.intValue();
                    if (newNum.intValue() <= 0) {
                        /*接口推送数量超过限制*/
                        redisClient.hset("ald-" + channelCode, "out_limit_" + userInfo.getAreaCode(), "Y");
                    }
                } else if (code.intValue() == Constants.BUSINESS_STATUS_OUT_LIMIT) {
                    /*接口推送数量超过限制*/
                    redisClient.hset("ald-" + channelCode, "out_limit_" + userInfo.getAreaCode(), "Y");
                }
                String iolStatus = redisClient.hget("ald-" + channelCode, "out_limit_" + userInfo.getAreaCode());
                if ("Y".equals(iolStatus) || "Y".equals(flag)) {
                    /*更新数据库*/
                    KwAreaData kwAreaData = new KwAreaData();
                    kwAreaData.setChannelCode(channelCode);
                    kwAreaData.setOutLimit(iolStatus);
                    kwAreaData.setAreaCode(userInfo.getAreaCode());
                    kwAreaDataService.updateOutLimit(kwAreaData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
    }


    public void testRedis() {
        redisClient.lpush("dcMQlinkwechat", "15835132986");
        redisClient.lpush("dcMQlinkwechat", "13120140358");
        /*redisClient.lpush("dcMQlinkmarketing","15835132986");
        redisClient.lpush("dcMQlinkmarketing","13120140358");
*/
        boolean flag = true;
        while (flag) {
            List<String> list = redisClient.blpop(1, "delaysms");
            if (list != null && list.size() > 1) {
                String mobile = list.get(1);
                if (StringUtils.isNotBlank(mobile)) {
                    logger.info(mobile);
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }

    }

    /**
     * 发送积压短信
     */
    public void sendStockSMS() throws Exception {
        /**关注公众号*/
        boolean flag = true;
        while (flag) {
            List<String> list = redisClient.blpop(1, "dcMQlinkwechat");
            if (list != null && list.size() > 1) {
                String mobile = list.get(1);
                if (StringUtils.isNotBlank(mobile) && ValidatorUtil.isMobile(mobile)) {
                    /*String text = "【卡王贷】感谢您申请卡王贷，请用微信搜索并关注公众号“秒分配”，查询贷款进度，另有更多优质贷款产品为您推荐。退订回T";
                    smsService.singleFollowSend(mobile, text);*/
                    String url = ConfigUtil.getConfig("sms.send.url");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("phoneNumber", mobile);
                    jsonObject.put("templateCode", "SMS_05");
                    HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        /**营销短信*/
        flag = true;
        while (flag) {
            List<String> list = redisClient.blpop(1, "dcMQlinkmarketing");
            if (list != null && list.size() > 1) {
                String mobile = list.get(1);
                if (StringUtils.isNotBlank(mobile) && ValidatorUtil.isMobile(mobile)) {
                    User user = userService.getByMobile(mobile);
                    String name = user.getName();
                    if (StringUtils.isBlank(name)) {
                        name = "老铁";
                    }
                    /*String text = "【卡王贷】尊敬的" + name + ",根据您的资金需求及信用情况,您获得50000元贷款资格,戳 http://t.cn/RkPqcEH 申请。退订回T";
                    smsService.singleSendMarketing(mobile, text);*/
                    String url = ConfigUtil.getConfig("sms.send.url");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("phoneNumber", mobile);
                    jsonObject.put("templateCode", "SMS_06");
                    JSONObject templateParam = new JSONObject();
                    templateParam.put("name", name);
                    jsonObject.put("templateParam", templateParam);
                    HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
    }


    @EventListener(condition = "#event.tag=='mdzj_add_product'")
    public void mdzjAddProduct(RocketmqEvent event) throws Exception {
        try {
            logger.debug("EventListener mdzj_add_product");
            JSONObject jsonObject = JSON.parseObject(event.getMsg());
            String uuid = jsonObject.getString("uuid");
            logger.debug("uuid:{} jsonObject:{}", uuid, jsonObject);
            String mobile = jsonObject.getString("mobile");
            String city = jsonObject.getString("city");
            String name = jsonObject.getString("name");
            String id_card = jsonObject.getString("idCard");
            Integer sex = jsonObject.getIntValue("sex");
            BigDecimal expect_amount = jsonObject.getBigDecimal("expectAmount");
            Integer policy = jsonObject.getIntValue("policy");
            Integer credit = jsonObject.getIntValue("credit");
            Integer house = jsonObject.getIntValue("house");
            Integer car = jsonObject.getIntValue("car");
            Integer fund = jsonObject.getIntValue("fund");
            Integer social_security = jsonObject.getIntValue("socialSecurity");
            Integer occupation = jsonObject.getIntValue("occupation");
            Integer salary_method = jsonObject.getIntValue("salaryMethod");
            Integer work_duration = jsonObject.getIntValue("workDuration");
            Integer salary = jsonObject.getIntValue("salary");
            Integer wxloan = jsonObject.getIntValue("wxloan");
            Date birthday = DateUtils.strToDate("1990-06-05", "yyyy-MM-dd");
            if (StringUtils.isNotBlank(jsonObject.getString("birthday"))) {
                try {
                    long datevalue = Long.parseLong(jsonObject.getString("birthday"));
                    birthday = new Date(datevalue);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String mobile_registration = jsonObject.getString("mobileRegistration");
            String ip = jsonObject.getString("ip");
            Integer areaCode = jsonObject.getInteger("areaCode");
            String areaName = jsonObject.getString("areaName");
            Date applyDate = new Date();
            if (StringUtils.isNotBlank(jsonObject.getString("createDate"))) {
                try {
                    long datevalue = Long.parseLong(jsonObject.getString("createDate"));
                    applyDate = new Date(datevalue);
                } catch (Exception e) {

                }
            }
            String channel_id = jsonObject.getString("channelId");
            String channel_code = jsonObject.getString("channelCode");
            String channel_name = jsonObject.getString("channelName");

            User user = new User();
            user.setName(name);
            user.setMobile(mobile);
            user.setSex(sex);
            user.setCity(city);
            user.setBirthday(birthday);
            user.setAge(getAge(birthday));
            user.setIp(ip);
            user.setChannelId(channel_id);
            user.setChannelCode(channel_code);
            user.setChannelName(channel_name);
            userService.insert(user);
            //用户详细信息
            UserInfo userInfo = new UserInfo();
            //使用mdzj 的uuid
            userInfo.setId(uuid);
            userInfo.setUserId(user.getId());
            userInfo.setRealName(name);
            userInfo.setIdCard(id_card);
            userInfo.setExpectAmount(expect_amount);
            userInfo.setPolicy(policy);
            userInfo.setCredit(credit);
            userInfo.setHouse(house);
            userInfo.setCar(car);
            userInfo.setFund(fund);
            userInfo.setSocialSecurity(social_security);
            userInfo.setOccupation(occupation);
            userInfo.setSalaryMethod(salary_method);
            userInfo.setWorkDuration(work_duration);
            userInfo.setSalary(salary);
            userInfo.setWxloan(wxloan);
            userInfo.setBirthday(birthday);
            userInfo.setBusinessDuration(1);
            userInfo.setMobileRegistration(mobile_registration);
            userInfo.setIp(ip);
            userInfo.setAreaCode(areaCode);
            userInfo.setAreaName(areaName);
            userInfo.setScity(city);
            insert(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
    }


}
